package com.aaie.gru.theme.controller;


import com.aaie.gru.gruenum.UserType;
import com.aaie.gru.response.ResMessage;
import com.aaie.gru.theme.entity.GruSysTheme;
import com.aaie.gru.theme.entity.GruSysThemeConfig;
import com.aaie.gru.theme.entity.GruSysThemeDto;
import com.aaie.gru.theme.service.IGruSysThemeConfigService;
import com.aaie.gru.theme.service.IGruSysThemeService;
import com.aaie.gru.user.entity.GruSysStuDto;
import com.aaie.gru.util.CommonUtil;
import com.aaie.gru.util.ConstantUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lvxing
 * @since 2019-08-09
 */
@Api(tags = "主题模块")
@RestController
@RequestMapping("/theme")
public class GruSysThemeController {

    @Autowired
    IGruSysThemeService gruSysThemeService;

    @Autowired
    IGruSysThemeConfigService iGruSysThemeConfigService;

    /**
     * 按条件获取主题信息
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "获取主题列表", notes = "获取主题列表")
    @PostMapping("/getGruSysThemeList")
    public String getGruSysThemeList(@RequestBody GruSysThemeDto param,HttpSession session) {
        try {
            String currentUserId = CommonUtil.getUser(session).getUserId();
            // 定义分页
            Page<GruSysTheme> paramPage = new Page<>(param.getCurrent(), param.getSize());
            // 查询条件
            QueryWrapper<GruSysTheme> queryWrapper = new QueryWrapper<>();
            String roleNameStr = CommonUtil.getUser(session).getUserType();


            if(StringUtils.equals(ConstantUtil.ROLE_NAME_PARENT,roleNameStr)){
                if(StringUtils.isNotEmpty(param.getCreateId())){
                    queryWrapper.eq("create_id",param.getCreateId());
                }
                queryWrapper.eq(StringUtils.isNotEmpty(param.getCreateName()), "create_name", param.getCreateName());
            }

            queryWrapper.like(StringUtils.isNotEmpty(param.getSearch()), "theme_content", param.getSearch());
            // 按更新时间倒叙排序
            queryWrapper.orderByDesc("update_time_sort");
            IPage<GruSysTheme> page = gruSysThemeService.page(paramPage,queryWrapper);
            List<GruSysTheme> gruSysThemeList = page.getRecords();
            List<GruSysTheme> grySysThemeListResult = new ArrayList<>();
            for(int i = 0,count = gruSysThemeList.size();i < count;i ++){
                GruSysTheme gruSysTheme = gruSysThemeList.get(i);
                QueryWrapper<GruSysThemeConfig> queryWrapperGrySysThemeConfig = new QueryWrapper<>();
                queryWrapperGrySysThemeConfig.eq("theme_id",gruSysTheme.getThemeId());
                queryWrapperGrySysThemeConfig.eq("current_user_id",currentUserId);
                GruSysThemeConfig gruSysThemeConfig = iGruSysThemeConfigService.getOne(queryWrapperGrySysThemeConfig);
                if(gruSysThemeConfig != null){
                    gruSysTheme.setThemeNew(gruSysThemeConfig.getThemeNew());
                }

                grySysThemeListResult.add(gruSysTheme);
            }
            return ResMessage.ok(grySysThemeListResult, param.getCurrent(), param.getSize(), page.getTotal());
        } catch (BeansException e) {
            e.printStackTrace();
            return ResMessage.error("/theme/getGruSysThemeList报错", 500);
        }

    }

    @ApiOperation(value = "获取主题未读消息数量", notes = "获取主题未读消息数量")
    @PostMapping("/getThemeNewCount")
    public String getThemeNewCount(@RequestBody GruSysStuDto param, HttpSession session){
        int count = 0;
        try{
            String currentUserId = CommonUtil.getUser(session).getUserId();
            QueryWrapper<GruSysThemeConfig> queryWrapperGrySysThemeConfig = new QueryWrapper<>();
            queryWrapperGrySysThemeConfig.eq("current_user_id",currentUserId);
            queryWrapperGrySysThemeConfig.eq("theme_new",ConstantUtil.THEME_NEW_Y);
            count = iGruSysThemeConfigService.count(queryWrapperGrySysThemeConfig);
            if(count > 0){
                count = 1;
            }
        }catch (Exception e){
            return ResMessage.error("/theme/getThemeNewCount报错", 500);
        }


        return ResMessage.ok(count);
    }

    /**
     * 添加主题数据
     *
     * @param gruSysTheme
     * @return
     */
    @ApiOperation(value = "添加主题数据", notes = "添加主题数据")
    @PostMapping("/addGruSysTheme")
    public String addGruSysTheme(@RequestBody GruSysTheme gruSysTheme, HttpSession session) {
        try {
            if (StringUtils.isNotEmpty(gruSysTheme.getThemeId())) {
                return ResMessage.error("新增的数据不能有主键id", 200);
            }
            // 主题内容不能为空
            if (StringUtils.isEmpty(gruSysTheme.getThemeContent())) {
                return ResMessage.error("主题内容不能为空", 200);
            }
            String updateTime = CommonUtil.generateLocalDateTime();
            long updateTimeSort = CommonUtil.generateCurrentTimeMillis();
            gruSysTheme.setCreateId(CommonUtil.getUser(session).getUserId());
            gruSysTheme.setCreateName(CommonUtil.getUser(session).getUserName());
            gruSysTheme.setCreateTime(updateTime);
            gruSysTheme.setCreateTimeSort(updateTimeSort);
            gruSysTheme.setUpdateName(CommonUtil.getUser(session).getUserName());
            gruSysTheme.setUpdateTime(updateTime);
            gruSysTheme.setUpdateTimeSort(updateTimeSort);
            boolean save = gruSysThemeService.save(gruSysTheme);
            if (!save) {
                return ResMessage.error("数据插入失败", 200);
            }
            return ResMessage.ok(gruSysTheme);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/addGruSysTheme报错", 500);
        }
    }

    /**
     * 更新主题数据
     *
     * @param gruSysTheme
     * @return
     */
    @ApiOperation(value = "更新主题数据", notes = "更新主题数据")
    @PostMapping("/editGruSysTheme")
    public String editGruSysTheme(@RequestBody GruSysTheme gruSysTheme, HttpSession session) {
        try {
            if (StringUtils.isEmpty(gruSysTheme.getThemeId())) {
                return ResMessage.error("更新的数据必须有主键id", 200);
            }
            // 主题内容不能为空
            if (StringUtils.isEmpty(gruSysTheme.getThemeContent())) {
                return ResMessage.error("主题内容不能为空", 200);
            }
            // 创建人只能取用户账号，不取用户名称了，因为用户名称不是同一个字段，取起来太麻烦
            gruSysTheme.setUpdateName(CommonUtil.getUser(session).getUserName());
            gruSysTheme.setUpdateTime(CommonUtil.generateLocalDateTime());
            gruSysTheme.setUpdateTimeSort(CommonUtil.generateCurrentTimeMillis());
            boolean b = gruSysThemeService.updateById(gruSysTheme);
            if (!b) {
                return ResMessage.error("数据更新失败", 200);
            }
            return ResMessage.ok(gruSysTheme);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/editGruSysTheme报错", 500);
        }

    }

    @ApiOperation(value = "按id获取题数据", notes = "按id获取题数据")
    @GetMapping("/getGruSysTheme")
    public String getGruSysTheme(String themeId,HttpSession session) {
        try {
            if (StringUtils.isEmpty(themeId)) {
                return ResMessage.error("获取数据必须有主键id", 200);
            }
            GruSysTheme gruSysTheme = gruSysThemeService.getById(themeId);

            if (gruSysTheme == null) {
                return ResMessage.error("获取失败", 500);
            }
            return ResMessage.ok(gruSysTheme);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/getGruSysTheme报错", 500);
        }

    }

    @ApiOperation(value = "删除主题数据", notes = "删除主题数据")
    @PostMapping("/delGruSysTheme")
    public String delGruSysTheme(@RequestBody GruSysTheme gruSysTheme) {
        try {
            if (StringUtils.isEmpty(gruSysTheme.getThemeId())) {
                return ResMessage.error("删除数据必须有主键id", 200);
            }
            // 物理删除 删除主题的同时也删除主题对应的反馈内容
            boolean b = gruSysThemeService.delGruSysThemeById(gruSysTheme.getThemeId());
            if (b) {
                return ResMessage.ok("删除数据成功");
            }
            return ResMessage.error("删除数据失败", 200);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/delGruSysTheme报错", 500);
        }

    }

}
